﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Interactivity;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace LogoFX.Infra.Interactivity
{
    public class TakeFocusOnVisibleBehavior : Behavior<Control>
    {
        public Visibility TargetVisibility
        {
            get { return (Visibility) GetValue(TargetVisibilityProperty); }
            set { SetValue(TargetVisibilityProperty, value); }
        }

        // Using a DependencyProperty as the backing store for TargetVisibility.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TargetVisibilityProperty =
            DependencyProperty.Register("TargetVisibility", typeof (Visibility), typeof (TakeFocusOnVisibleBehavior),
                                        new PropertyMetadata(Visibility.Collapsed, VisibilityChanged));

        private static void VisibilityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            TakeFocusOnVisibleBehavior tfovb = (TakeFocusOnVisibleBehavior) d;
            if (tfovb.TargetVisibility == Visibility.Visible)
                tfovb.AssociatedObject.Focus();
        }


        protected override void OnAttached()
        {
            base.OnAttached();
            BindingOperations.SetBinding(this, TargetVisibilityProperty,
                                         new Binding("Visibility") {Source = AssociatedObject});


        }


        protected override void OnDetaching()
        {
            base.OnDetaching();


        }
    }
}
